using System;
using System.Diagnostics;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;

namespace TeamDeploy.Tasks
{
    public class Uninstall : TaskBase
    {
        public override bool Execute()
        {
            try
            {
                if (!System.IO.File.Exists(RemoteExecutePathFilename))
                {
                    Log.LogError("RemoteExecute does not exists at: " + RemoteExecutePathFilename);
                    return false;
                }

                Log.LogMessage("In Uninstall.Execute()");

                string uninstallArgs = "/qn /x";
                string args = @"\\" + TargetMachine + " -i 0 -s -accepteula " + "msiexec.exe " + uninstallArgs + " " + ProductCode;

                Process p = Process.Start(RemoteExecutePathFilename, args);
                p.WaitForExit();

                if (p.ExitCode != 0)
                {
                    string message = "Uninstalling " + ProductCode + " on " + TargetMachine + " returned code:" + p.ExitCode;

                    if (ignoreExitCode)
                    {
                        Log.LogMessage(message);
                    }
                    else
                    {
                        Log.LogError(message);
                        return false;
                    }
                }

                if (BuildEngine != null)
                {
                    Log.LogMessage("Uninstalling " + ProductCode + " on " + TargetMachine + " completed successfully.");
                }
                return true;
            }
            catch (Exception ex)
            {
                if (BuildEngine != null)
                {
                    Log.LogError("Error executing Uninstall: ProductCode=" + ProductCode + " TargetMachine=" +
                                 TargetMachine + " RemoteExecutePathFilename=" + RemoteExecutePathFilename + ":::" +
                                 ex);
                }
                return false;
            }
        }

        [Required]
        public string ProductCode { get; set; }

        [Required]
        public string TargetMachine { get; set; }

        [Required]
        public string RemoteExecutePathFilename { get; set; }
    }
}
